<template>
	<view class="home_scan">
		<button class="scan_btn" @click="takePhoto" :disabled="isUpload">识别</button>
	</view>
</template>

<script>
	import Compressor from 'compressorjs';
	export default {
		data() {
			return {
				isUpload: false
			}
		},
		methods: {
			// 点击事件，触发拍照或从相册选择图片
			takePhoto() {
				uni.chooseImage({
					count: 1, // 默认9，设置图片的数量
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'], // 可以指定来源是相机还是相册，默认二者都有
					success: (res) => {
						// 成功选择图片后上传图片
						const tempFilePaths = res.tempFilePaths;
						this.compressImage(tempFilePaths[0], (compressedImagePath) => {
							// 在这里执行上传操作
							this.uploadImage(compressedImagePath);
						});
					},
					fail: (err) => {
						console.log('Error while choosing image:', err);
					}
				});
			},
			// 上传图片到服务器
			uploadImage(imagePath) {
				uni.showLoading({
					title: "上传中..."
				})
				this.isUpload = true
				uni.uploadFile({
					url: 'http://1.12.222.66/api/ocr/extract-text', // 服务器上传接口地址
					filePath: imagePath, // 要上传文件资源的路径
					name: 'file', // 必填，文件对应的 key
					formData: null,
					success: (uploadRes) => {
						console.log("uploadRes", uploadRes)
						let data = JSON.parse(uploadRes.data)
						if (data && data.code == '0') {
							this.isUpload = false
							uni.hideLoading()
							if (data.result) {
								uni.navigateTo({
									url: "/pages/scancode/index?resData=" + encodeURIComponent(JSON
										.stringify(data.result)),
								})
							} else {
								uni.showToast({
									title: '未识别到信息,请重新上传',
									icon: 'error',
									duration: 2000
								});
							}

						} else {
							uni.hideLoading()
							this.isUpload = false
							uni.showToast({
								title: data.msg || '上传失败',
								icon: 'error',
								duration: 2000
							});
						}

					},
					fail: (uploadErr) => {
						uni.hideLoading()
						this.isUpload = false
					}
				});

				// // 如果需要取消上传任务
				// // uploadTask.abort();
			},
			compressImage(src, callback) {
				const img = new Image();
				img.src = src;
				img.onload = () => {
					const canvas = document.createElement('canvas');
					const ctx = canvas.getContext('2d');
					const width = img.width;
					const height = img.height;
					canvas.width = width;
					canvas.height = height;
					ctx.drawImage(img, 0, 0, width, height);
					canvas.toBlob((blob) => {
						if (blob) {
							let newImagePath = URL.createObjectURL(blob);
							callback(newImagePath);
						}
					}, 'image/jpeg', 0.1); // 0.7为压缩质量，可以根据需要调整
				};
			},
		}
	}
</script>

<style lang="scss">
	.home_scan {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		/* 确保容器宽度为百分比 */
		height: 100%;
		/* 设置一个高度 */
		background-image: url("../../static/homebg.png");
		/* 背景图片路径 */
		background-size: cover;
		/* 背景图片覆盖整个容器 */
		background-position: center;
		/* 背景图片居中 */
		overflow: hidden;
	}

	.scan_btn {
		position: fixed;
		left: calc(50% - 100px);
		bottom: 100px;
		width: 200px;
		display: inline-block;
		line-height: 1;
		white-space: nowrap;
		cursor: pointer;
		color: #fff;
		background-color: #409eff;
		border-color: #409eff;
		-webkit-appearance: none;
		text-align: center;
		box-sizing: border-box;
		outline: none;
		margin: 0;
		transition: .1s;
		font-weight: 500;
		-moz-user-select: none;
		-webkit-user-select: none;
		-ms-user-select: none;
		padding: 12px 20px;
		font-size: 14px;
		border-radius: 20px;
	}
</style>